package edu.neu.cs6515.xml.converter;

import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

import edu.neu.cs6515.xml.Placement;
import edu.neu.cs6515.xml.w12.AdministratorResponses;
import edu.neu.cs6515.xml.w12.PlayerActions;
import edu.neu.cs6515.xml.w12.ReRackPlease;
import edu.neu.cs6515.xml.w12.Rerackable;

public class ActionConverter implements Converter {

    @Override
    public boolean canConvert(final Class type) {
        return PlayerActions.class.equals(type);
    }

    @Override
    public void marshal(final Object source,
            final HierarchicalStreamWriter writer,
            final MarshallingContext context) {
        PlayerActions pa = (PlayerActions) source;
        for (Object obj : pa.getActions()) {
            if (obj instanceof Placement) {
                writer.startNode("placement");
                context.convertAnother(obj);
                writer.endNode();
            } else if (obj instanceof Rerackable) {
                writer.startNode("rerackable");
                writer.endNode();
            } else {
                writer.startNode("rerack");
                writer.endNode();
            }
        }
    }

    @Override
    public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
        List<Object> list = new ArrayList<Object>();

        while (reader.hasMoreChildren()) {
            reader.moveDown();
            String nodeName = reader.getNodeName();
            if (nodeName.equals("rerack")) {
                list.add(new ReRackPlease());
            } else if (nodeName.equals("rerackable")) {
                list.add(new Rerackable());
            } else {
                Placement p = (Placement) new PlacementConverter().unmarshal(reader, context);
                list.add(p);
            }
            reader.moveUp();
        }
        PlayerActions ar = new PlayerActions(list);
        return ar;
    }

}